package com.questions.helper.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.questions.helper.MainActivity;
import com.questions.helper.R;
import com.questions.helper.application.QuestionsHelperApplication;
import com.questions.helper.model.AccessibilityNodeInfoHierarchy;
import com.questions.helper.model.Answer;
import com.questions.helper.model.Questions;
import com.questions.helper.util.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;
import java.util.stream.Collectors;

@SuppressLint("AccessibilityPolicy")
public class QuestionsHelperService extends AccessibilityService {
    private static final String TAG = "QuestionsHelperService";
    private static QuestionsHelperApplication questionsHelperApplication;

    public static boolean isServiceEnabled(android.content.Context context) {

        // 检查服务是否实际运行
        android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(android.content.Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (QuestionsHelperService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }

        // 备用方法：检查无障碍服务状态
        android.content.ContentResolver contentResolver = context.getContentResolver();
        String enabledServices = android.provider.Settings.Secure.getString(contentResolver,
                android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);

        return enabledServices != null && enabledServices.contains(context.getPackageName() + "/" + QuestionsHelperService.class.getName());
    }
    @Override
    public void onCreate() {
        super.onCreate();
        questionsHelperApplication = QuestionsHelperApplication.questionsHelperApplication;
        questionsHelperApplication.setQuestionsHelperService(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendBroadcast(new Intent("com.questions.helper.ACCESSBILITY_DISCONNECT"));
        Toast.makeText(this, "中断答题助手服务", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if(event.getEventType()==AccessibilityEvent.TYPE_VIEW_CLICKED){
            AccessibilityNodeInfo source = event.getSource();
            if(source==null){
                return;
            }
            CharSequence text = source.getText();
            if(text==null){
                return;
            }
            Log.i(this.getPackageName(),source.getText().toString());
            String texzt = source.getText().toString();
            if(texzt.contains("单选题")||texzt.contains("多选题")||texzt.contains("判断题")){
                Intent intent = new Intent(MainActivity.ACTION_SERVICE_CLEAR_CANVAS);
                sendBroadcast(intent);
                this.getCurrentWindowViewInfos();
            }else if(texzt.contains("上一题")||texzt.contains("下一题")||texzt.contains("无")||texzt.contains("答题卡")||texzt.contains("+ 交卷")){
                Intent intent = new Intent(MainActivity.ACTION_SERVICE_CLEAR_CANVAS);
                sendBroadcast(intent);
            }
        }else if(event.getEventType()==AccessibilityEvent.TYPE_VIEW_SCROLLED){
            Log.i(this.getPackageName(),"滑动了 x="+event.getScrollX()+"  y="+event.getScrollY());
            if(questions==null){
                return;
            }
            Intent intent = new Intent(MainActivity.ACTION_SERVICE_CLEAR_CANVAS);
            sendBroadcast(intent);
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            AccessibilityNodeInfo accessibilityNodeInfo = findNodeInfo(rootNode);
            AccessibilityNodeInfo questionsTypeNodeInfo = accessibilityNodeInfo.getChild(8);//题型  第13行 第8列
            AccessibilityNodeInfo questionsAndAnswerNodeInfo =accessibilityNodeInfo.getChild(11);
            Rect bounds = new Rect();
            questionsTypeNodeInfo.getBoundsInScreen(bounds);
            findA(questionsAndAnswerNodeInfo,questionsTypeNodeInfo,bounds);
        }
    }

    void findA(AccessibilityNodeInfo questionsAndAnswerNodeInfo,AccessibilityNodeInfo questionsTypeNodeInfo,Rect bounds){
        List<Answer> answerList = questions.getAnswers();
        String ss = answerList.stream().map(Answer::getTitleText).collect(Collectors.joining(","));
        Log.i(this.getPackageName(),ss);
        List<String> xsd=new ArrayList<>();
        if("多选题".contentEquals(questionsTypeNodeInfo.getText())){
            AccessibilityNodeInfo accessibilityNodeInfoAnswer = questionsAndAnswerNodeInfo.getChild(2);
            int childCount = accessibilityNodeInfoAnswer.getChildCount();
            for(int i = 0;i<childCount;i++){
                xsd.add(showText(answerList, accessibilityNodeInfoAnswer.getChild(i)));
            }
        }else {
            int childCount = questionsAndAnswerNodeInfo.getChildCount();
            for(int i = 1;i<childCount;i++){ //第14行 第2列
                AccessibilityNodeInfo accessibilityNodeInfoAnswer = questionsAndAnswerNodeInfo.getChild(i);
                if("android.widget.RadioGroup".contentEquals(accessibilityNodeInfoAnswer.getClassName())){
                    xsd.add(showText(answerList,accessibilityNodeInfoAnswer.getChild(0).getChild(0)));
                }
            }
        }
        String text = xsd.stream().filter(v->!v.isEmpty()).collect(Collectors.joining(","));
        Log.i(this.getPackageName(),text);
        Intent intent_ = new Intent(MainActivity.ACTION_SERVICE_MOVE);
        if(text.isEmpty()){
            intent_.putExtra(MainActivity.MOVE_DATA,""+bounds.top);
        }else {
            intent_.putExtra(MainActivity.MOVE_DATA,text);
        }
        sendBroadcast(intent_);
    }

    @Override
    public void onInterrupt() {
        Log.d(TAG, "QuestionsHelperService  interrupt");
        Toast.makeText(this, "中断答题助手服务", Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        sendBroadcast(new Intent("com.questions.helper.ACCESSBILITY_CONNECT"));
        Toast.makeText(this, "已连接学习答题助手服务", Toast.LENGTH_SHORT).show();
    }

    private AccessibilityNodeInfo findNodeInfo(AccessibilityNodeInfo rootNode){
        Stack<AccessibilityNodeInfoHierarchy> accessibilityNodeInfoStack = new Stack<>();
        accessibilityNodeInfoStack.push(new AccessibilityNodeInfoHierarchy(rootNode,0,0));
        while (!accessibilityNodeInfoStack.isEmpty()){
            AccessibilityNodeInfoHierarchy accessibilityNodeInfoHierarchy = accessibilityNodeInfoStack.pop();
            int row_ = accessibilityNodeInfoHierarchy.getRow();
            AccessibilityNodeInfo sub = accessibilityNodeInfoHierarchy.getAccessibilityNodeInfo();
            if("android.widget.Button".contentEquals(sub.getClassName())){
                AccessibilityNodeInfo pp = sub.getParent().getParent();
                if("android.widget.RadioGroup".contentEquals(pp.getClassName()))
                    return pp.getParent().getParent();
                else
                    return pp.getParent();
            }
            int childCount = sub.getChildCount();
            for(int i = 0;i<childCount;i++){
                accessibilityNodeInfoStack.push(new AccessibilityNodeInfoHierarchy(sub.getChild(i),row_+1,i));
            }
        }
        throw  new RuntimeException("没有找到按钮标签");
    }

    Thread thread;
    public void getCurrentWindowViewInfos() {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        thread = new Thread(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignored) {}
            if (rootNode != null) {
               try{
                   questions=null;
                   checkTheAnswer(rootNode);
               }catch (Exception e){
                   Log.e(this.getPackageName(), Objects.requireNonNull(e.getMessage()));
               }finally {
                   rootNode.refresh();
               }
            }else {
                Toast.makeText(QuestionsHelperApplication.questionsHelperApplication, R.string.questions_not_find, Toast.LENGTH_SHORT).show();
            }
        });
        thread.start();
    }

    Questions questions;
    private void checkTheAnswer(AccessibilityNodeInfo rootNode){
        AccessibilityNodeInfo accessibilityNodeInfo = findNodeInfo(rootNode);
        AccessibilityNodeInfo questionsTypeNodeInfo = accessibilityNodeInfo.getChild(8);//题型  第13行 第8列
        AccessibilityNodeInfo questionsAndAnswerNodeInfo =accessibilityNodeInfo.getChild(11);
        AccessibilityNodeInfo questionsNodeInfo =  questionsAndAnswerNodeInfo.getChild(0);//题目 第14行 第0列
        String text1 = Utils.formText(questionsNodeInfo.getText());
        Log.i(this.getPackageName(),text1);
        questions = questionsHelperApplication.getLegalknowledgeSQLite().getOneQuestions(text1);
        Rect bounds = new Rect();
        questionsTypeNodeInfo.getBoundsInScreen(bounds);
        if(questions==null){
            Log.i(this.getPackageName(),""+bounds.top);
            Intent intent = new Intent(MainActivity.ACTION_SERVICE_MOVE);
            intent.putExtra(MainActivity.MOVE_DATA,""+bounds.top);
            sendBroadcast(intent);
        }else {
            findA(questionsAndAnswerNodeInfo,questionsTypeNodeInfo,bounds);
        }
    }

    private String showText(List<Answer> answerList, AccessibilityNodeInfo source){
        String text = Utils.formText(source.getText()).substring(1);
        if("对".equals(text)){
            text="正确";
        }else if ("错".equals(text)){
            text="错误";
        }
        for (Answer v:answerList){
            if(text.equals(v.getTitleText())){
                Rect bounds = new Rect();
                source.getBoundsInScreen(bounds);
                return bounds.top+"";
            }
        }
        return "";
    }

}
